package com.tenglong.teacher.ui;

import android.content.SharedPreferences;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.os.Bundle;
import android.view.View;

import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.Density;
import com.cuotibao.zhuoxiao.basics.utils.IpUtils;
import com.tenglong.teacher.R;
import com.tenglong.teacher.ui.utils.MyPreference;

public class DebugActivity extends PreferenceActivity implements View.OnClickListener, Preference.OnPreferenceChangeListener {

    private ListPreference mListPreference;
    private MyPreference myPreference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Density.setDensity(getApplication(), this);
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferenc);
        initPreferences();
        setListeners();
    }

    private void setListeners() {
        mListPreference.setOnPreferenceChangeListener(this);
        myPreference.setOnClickListener(this);
    }

    private void initPreferences() {
        mListPreference = (ListPreference) findPreference("domainIndex");
        myPreference = (MyPreference) findPreference("userInfo");
        SharedPreferences spDebugMode = getSharedPreferences("debug_mode", 0);
        int index = spDebugMode.getInt(GlobalConstant.KEY_DEBUG_INDEX, 0);
        mListPreference.setValueIndex(index);
        mListPreference.setSummary(mListPreference.getEntries()[index]);
    }

    @Override
    public void onClick(View v) {
        finish();
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        if (preference instanceof ListPreference) {
            ListPreference listPreference = (ListPreference) preference;
            CharSequence[] entries = listPreference.getEntries();
            int index = listPreference.findIndexOfValue((String) newValue);
            listPreference.setSummary(entries[index]);
            SharedPreferences spDebugMode = getSharedPreferences("debug_mode", 0);
            SharedPreferences.Editor ed = spDebugMode.edit();
            ed.putInt(GlobalConstant.KEY_DEBUG_INDEX, index);
            ed.commit();
            IpUtils.IpIndex = index;
        }
        return true;
    }
}
